package cn.echo.ecc.mq.listener;

import cn.echo.ecc.domain.CourseOrder;
import cn.echo.ecc.dto.PayDto;
import cn.echo.ecc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-course-order-producer-group")
public class CourseOrderTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 执行本地事务
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            log.info("开始执行本地事务！");
            if (arg == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 转换参数类型
            CourseOrder courseOrder = JSON.parseObject(arg.toString(), CourseOrder.class);
            String orderNo = courseOrder.getOrderNo();
            // 加同步锁，保证线程安全，订单编号唯一
            synchronized (orderNo) {
                if (courseOrderService.selectByOrderNo(orderNo) != null) {
                    log.info("课程订单已经存在！");
                    return RocketMQLocalTransactionState.ROLLBACK;
                }
                // 新增课程订单和订单快照
                courseOrderService.saveCourseOrderAndCourseOrderItem(courseOrder);
            }
            log.info("本地事务执行成功！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("本地事务执行失败！");
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            log.info("开始回查本地事务执行结果！");
            // 防御性编程
            byte[] bytes = (byte[])message.getPayload();
            if (bytes == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 转换参数类型，业务校验
            String strParam = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(strParam, PayDto.class);
            if (payDto == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 回查本地事务执行结果
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(payDto.getOrderNo());
            if (courseOrder == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            log.info("回查本地事务执行成功！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("回查本地事务执行失败！");
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
